<template>
	<!--  :style="{paddingBottom:`calc(${keyHeight}px + 18rpx)`}" -->
	<u-popup :show="show" @close="close" @open="open" mode="bottom" zIndex="10078" :overlayStyle="{zIndex:10075}"
		:safeAreaInsetBottom="false">
		<view class="comment_popup" :style="{bottom:`${keyHeight}px`}">
			<!-- 输入框 -->
			<view class="comment_input">
				<u-textarea placeholder="友善评论..." border="surround" v-model="content" autoHeight :cursor="cursor"
					@blur="cursorss" @focus="handlefocus" :showConfirmBar="false" :focus="izFocus"
					@keyboardheightchange="handleKeyboardheightchange" :adjustPosition="false"
					@touchstart="stopEvent"></u-textarea>
			</view>
			<!-- 图片 -->
			<view class="comment_img" v-if="record?.imagesUrl">
				<image :src="record?.imagesUrl"></image>
				<view class="comment_img_del" @click="handleDelImg">
					<u-icon name="close" color="#fff" size="10"></u-icon>
				</view>
			</view>
			<!-- 发送 -->
			<view class="comment_bom">
				<view>
					<image src="http://qianxueapplet.suoeryun.com/photo.png" @click="handleImage"></image>
					<image :src="`http://qianxueapplet.suoeryun.com/${izExpression?'emoji.png':'keyboard.png'}`"
						@click="handleExpression"></image>
				</view>
				<button class="comment_bom_btn" @click="handleSave()"
					:disabled="content === '' && !record?.imagesUrl">发送</button>
			</view>
			<!-- 表情 -->
			<view class="expression" v-show="izExpression">
				<scroll-view class="emojis_scroll" :scroll-x="false" :scroll-y="true">
					<view v-for="item in emojis" :key="item" class="emoji" @click="ChooseToLook(`${item}`)">
						{{item}}
					</view>
				</scroll-view>
			</view>
		</view>
	</u-popup>
</template>

<script setup lang="ts">
	import { ref, unref, defineEmits, getCurrentInstance, toRaw } from "vue";
	import { qxCommentAdd } from "@/config/index.api";
	import config from '@/common/config';

	const show = ref(false);
	const izFocus = ref(false);
	const izExpression = ref(false);
	const content = ref('');
	const record = ref();
	const cursor = ref(0);
	const emit = defineEmits(['success']);
	const { proxy } = getCurrentInstance();
	const keyHeight = ref(0);
	const emojis = ['🤞', '👍', '👏', '❤', '🖐', '😀', '😃',
		'😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇',
		'🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗',
		'😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨',
		'🧐', '🤓', '😎', '🤩', '🥳', '😏', '😒', '😞',
		'😔', '😟', '😕', '🙁', '😣', '😖', '😫', '😩',
		'🥺', '😢', '😭', '😤', '😠', '😡', '🤬', '🤯',
		'😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓',
		'🤗', '🤔', '🤭', '🤫', '🤥', '😶', '😐', '😑',
		'😬', '🙄', '😯', '😦', '😧', '😮', '😲', '😴',
		'🤤', '😪', '😵', '🤐', '🥴', '🤢', '🤮', '🤧',
		'😷', '🤒', '🤕', '🤑', '🤠', '👻', '🐧'];

	async function handleShow(item) {
		show.value = true;
		record.value = item;
		if (item?.expression) {
			izExpression.value = item?.expression;
		} else {
			setTimeout(_ => {
				izFocus.value = true;
			}, 500)
		}
		// console.log(izFocus.value, item);
	}

	function getKeyHeight(res) {
		const _sysInfo = uni.getSystemInfoSync();
		if (_sysInfo.platform === "android") {
			if (unref(record)?.imagesUrl?.length > 0) {
				keyHeight.value = _sysInfo.screenHeight - _sysInfo.windowHeight + 20;
				return
			}
			if (unref(record)?.expression) {
				let _heightDiff = _sysInfo.screenHeight - _sysInfo.windowHeight
				let _diff = res.height - _heightDiff
				keyHeight.value = _diff > 0 ? _diff : 0;
				return
			}
			keyHeight.value = 0;
		} else {
			let _heightDiff = _sysInfo.screenHeight - _sysInfo.windowHeight
			let _diff = res.height - _heightDiff
			keyHeight.value = _diff > 0 ? _diff : 0;
		}
	}

	/**
	 * 打开
	 */
	function open() {
		// uni.onKeyboardHeightChange(getKeyHeight)
		console.log('open');
	}

	/**
	 * 关闭
	 */
	function close() {
		console.log('close');
		show.value = false;
		izFocus.value = false;
		izExpression.value = false;
		// uni.onKeyboardHeightChange(getKeyHeight);
	}
	/**
	 * 发送
	 */
	async function handleSave() {
		if (uni.$u.trim(unref(content))) {
			uni.showLoading()
			const res = await qxCommentAdd({
				content: unref(content),
				...unref(record),
				location: unref(proxy['vuex_current_position'])?.ad_info?.province,
				replyType: unref(record)?.replyType ? unref(record)?.replyType : '1'
			});
			content.value = '';
			emit('success', unref(record), res);
			uni.hideLoading()
			close();
		} else {
			uni.showToast({
				icon: 'none',
				title: '不能发送发送空评论'
			})
		}

	}

	/**
	 * 添加图片
	 */
	function handleImage() {
		if (unref(record)?.imagesUrl) {
			return uni.showModal({
				title: '提示',
				content: '是否清空当前图片并重新添加',
				confirmColor: '#FF943C',
				success: function (res) {
					if (res.confirm) {
						record.value.imagesUrl = '';
						chooseImage();
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			})
		} else {
			chooseImage();
		}
	}

	/**
	 * 添加表情
	 */
	function handleExpression() {
		izExpression.value = !izExpression.value;
		izFocus.value = !izExpression.value;
	}

	/**
	 * 调用打开图片
	 */
	function chooseImage() {
		uni.chooseImage({
			count: 1,
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				console.log(tempFilePaths, 'tempFilePaths');
				uni.uploadFile({
					url: config.baseUrl + '/sys/common/obsUpload', //仅为示例，非真实的接口地址
					filePath: tempFilePaths[0],
					name: 'file',
					header: {
						'X-Access-Token': unref(proxy['vuex_token'])
					},
					success: (uploadFileRes) => {
						record.value.imagesUrl = JSON.parse(uploadFileRes.data)?.message;
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '接口异常！'
						})
					}
				});
			}
		});
	}

	/**
	 * 删除图片
	 */
	function handleDelImg() {
		record.value.imagesUrl = '';
	}

	/**
	 * 插入表情
	 */
	function ChooseToLook(val) {
		// 返回获取从0到光标位置的字符串
		let str = content.value.substring(0, cursor.value)
		// 将表情插入指定位置
		content.value = content.value?.replace(str, str + val)
		// 光标向后移动两位
		cursor.value += 2; //光标加2(表情是占两个位置)
	}

	/**
	 * 失去焦点
	 */
	function cursorss(event) {
		console.log(event.target.cursor);
		cursor.value = event.target.cursor //保存光标位置
		keyHeight.value = 0;
	}

	/**
	 * 聚焦
	 */
	function handlefocus(e) {
		console.log(e, 23);
		if (!izFocus.value) {
			izFocus.value = true;
		}
		izExpression.value = false;
		if (e.detail.height) {
			const height = e.detail.height;
			const _sysInfo = uni.getSystemInfoSync();
			const screenHeight = _sysInfo.screenHeight;
			const windowHeight = _sysInfo.windowHeight;
			if (_sysInfo.platform === "android") {
				console.log('android');
				keyHeight.value = height - 60;
				console.log(keyHeight.value, 'keyHeight.value');
				return
				// if (unref(izManualFocus)) {
				// 	// let _heightDiff = _sysInfo.screenHeight - _sysInfo.windowHeight
				// 	// let _diff = res.height - _heightDiff
				// 	// keyHeight.value = _diff > 0 ? _diff : 0;
				// 	keyHeight.value = height > 0 ? height : 0;
				// 	console.log(keyHeight.value);
				// 	return
				// }
				// keyHeight.value = 0;
			} else {
				let _heightDiff = screenHeight - windowHeight
				let _diff = height - _heightDiff
				keyHeight.value = _diff > 0 ? _diff : 0;
			}
		}
	}

	/**
	 * @param {Object} e
	 */
	function stopEvent(e) {
		e.stopPropagation();
		e.preventDefault();
	}

	/**
	 * 监听键盘
	 */
	function handleKeyboardheightchange(e) {
		// const res = e.detail;
		// const _sysInfo = uni.getSystemInfoSync();
		// if (_sysInfo.platform === "android") {
		// 	if (unref(record)?.imagesUrl?.length > 0) {
		// 		keyHeight.value = _sysInfo.screenHeight - _sysInfo.windowHeight + 20;
		// 		return
		// 	}
		// 	console.log('android');
		// 	if (unref(izManualFocus)) {
		// 		// let _heightDiff = _sysInfo.screenHeight - _sysInfo.windowHeight
		// 		// let _diff = res.height - _heightDiff
		// 		// keyHeight.value = _diff > 0 ? _diff : 0;
		// 		keyHeight.value = res.height > 0 ? res.height : 0;
		// 		console.log(keyHeight.value);
		// 		return
		// 	}
		// 	keyHeight.value = 0;
		// } else {
		// 	let _heightDiff = _sysInfo.screenHeight - _sysInfo.windowHeight
		// 	let _diff = res.height - _heightDiff
		// 	keyHeight.value = _diff > 0 ? _diff : 0;
		// }
	}

	defineExpose({
		handleShow,
	})
</script>
<style lang="scss" scoped>
	.comment_popup {
		background-color: #fff;
		padding: 18rpx 26rpx;
		position: fixed;
		width: calc(100% - 26rpx - 26rpx);

		.comment_input {
			background-color: #fff;
		}

		.comment_img {
			margin-top: 10px;
			position: relative;

			.comment_img_del {
				position: absolute;
				padding: 10rpx;
				background-color: #8C8E92;
				border-radius: 50%;
				top: 0;
				left: 60rpx;
				text-align: center;
				line-height: 100rpx;
			}

			image {
				width: 100rpx;
				height: 100rpx;
				border-radius: 24rpx;
			}
		}

		.comment_bom {
			color: #9E9E9E;
			padding: 14rpx 22rpx;
			font-size: 26rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-top: 10rpx;

			image {
				width: 48rpx;
				height: 48rpx;
				margin-right: 32rpx;
				vertical-align: text-top;

				&:last-child {
					margin-right: 0;
				}
			}

			.comment_bom_btn {
				// width: 172rpx;
				background-color: #FF943C;
				color: #fff;
				text-align: center;
				font-size: 28rpx;
				margin: 0;
				height: 56rpx;
				line-height: 56rpx;

				&[disabled]:not([type]) {
					opacity: 0.5;
				}
			}
		}

		.expression {
			height: 488rpx;
			background-color: #FAFAFA;

			.emojis_scroll {
				display: block;
				float: left;
				width: 100%;
				height: 400rpx;
				padding-left: 25rpx;
			}

			.emoji {
				display: block;
				float: left;
				width: 100rpx;
				height: 100rpx;
				font-size: 70rpx;
				text-align: center;
			}
		}
	}
</style>